package com.doudou.dubbo.demo;

import com.doudou.dubbo.demo.api.GreetingService;
import com.doudou.dubbo.demo.service.GreetingServiceImpl;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.rpc.RpcContext;

/**
 * @author zhaozw
 */
public class ApiConsumerInJvm {
    private static final ThreadPoolExecutor bizThreadPool = new ThreadPoolExecutor(8, 16, 1,
            TimeUnit.MINUTES, new SynchronousQueue<>(), new NamedThreadFactory("biz-thread-pool"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void exportService() throws InterruptedException {
        ServiceConfig<GreetingService> serviceServiceConfig = new ServiceConfig<>();
        serviceServiceConfig.setApplication(new ApplicationConfig("first-dubbo-provider"));
        serviceServiceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        serviceServiceConfig.setInterface(GreetingService.class);
        serviceServiceConfig.setRef(new GreetingServiceImpl());
        serviceServiceConfig.setVersion("1.0.0");
        serviceServiceConfig.setGroup("dubbo");
        serviceServiceConfig.export();
        System.out.println("server is started");
        Thread.currentThread().join();
    }

    public static void referService() {
        ReferenceConfig<GreetingService> referenceConfig = new ReferenceConfig<>();
        referenceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        referenceConfig.setInterface(GreetingService.class);
        referenceConfig.setTimeout(5000);
        referenceConfig.setVersion("1.0.0");
        referenceConfig.setGroup("dubbo");
        referenceConfig.setCheck(false);
        GreetingService greetingService = referenceConfig.get();
        RpcContext.getContext().setAttachment("company", "juzi");
        System.out.println("----------------------------->>>> " + greetingService.sayHello("world"));
    }

    public static void main(String[] args) throws InterruptedException {
        bizThreadPool.execute(() -> {
            try {
                exportService();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        Thread.sleep(1000);
        // Dubbo提供了一种本地服务暴露与引用的方式，在同一个JVM进程中同时发布与调用同一个服务时该方式会起作用
        // 如果当前JVM内要调用的服务在本JVM进程内有提供，则避免了一次远程过程调用，而是直接在JVM内进行通信
        referService();
    }
}
